package com.tacc.tyun.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageInfo;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.tacc.tyun.base.BaseConstant;
import com.tacc.tyun.model.MsgMenu;
import com.tacc.tyun.model.SysOss;
import com.tacc.tyun.model.info.ReturnInfo;
import com.tacc.tyun.service.SysOssService;
import com.tacc.tyun.util.*;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;


/**
 * 云存储
 * @author taocongcong
 * @create 2017-07-04 16:00
 */
@Controller
@RequestMapping("/sysOss")
public class SysOssController {

    private static Logger LOGGER= LoggerFactory.getLogger(SysOssController.class);

    @Autowired
    private SysOssService sysOssService;

    //查询
    @RequestMapping("/listPage")
    public ModelAndView list(){
        return new ModelAndView("oss/sysOssList");
    }

    //配置云存储
    @RequestMapping("/sysOssConfig")
    public ModelAndView sysOssConfig(){
        return new ModelAndView("oss/sysOssConfig");
    }

    @RequestMapping("/picture")
    public ModelAndView picture(){
        return new ModelAndView("oss/picture");
    }

    /**
     * 使用Gson
     * @param sysOss
     * @param pageInfo
     * @return
     */
    @RequestMapping(value = "/jsonList",method = RequestMethod.POST)
    @ResponseBody
    public String jsonListGon(SysOss sysOss, PageInfo<SysOss> pageInfo) throws Exception {
        int pageNum=(pageInfo.getPageNum()/pageInfo.getPageSize())+1;
        pageInfo.setPageNum(pageNum);
        pageInfo = sysOssService.pageInfo(sysOss, pageInfo.getPageSize(), pageInfo.getPageNum());

        JsonObject jsonObject=new JsonObject();
                jsonObject.addProperty("total",pageInfo.getTotal());
                if (pageInfo!=null && pageInfo.getList()!=null && pageInfo.getList().size()>0){
                    JsonObject row=null;
                    JsonArray rows=new JsonArray();
                    for (SysOss item:pageInfo.getList()){
                        row=new JsonObject();
                        row.addProperty("id",item.getId());
                        row.addProperty("url",item.getUrl());
                        String qrcodeUrl="";
                if (StringUtils.isEmpty(item.getQrcodeUrl())){
                    try {
                        QrcodeUtil qrcodeUtil=new QrcodeUtil();
                        qrcodeUrl = qrcodeUtil.qrcode(item.getUrl(),item.getUrl());
                        //更新
                        item.setQrcodeUrl(qrcodeUrl);
                        int i = sysOssService.updateByPrimaryKeySelective(item);
                        if (i<=0){
                            if (LOGGER.isDebugEnabled()){
                                LOGGER.debug("生成二维码保存失败");
                            }
                        }
                    }catch (Exception e){
                        //生成二维码失败
                        e.printStackTrace();
                        if (LOGGER.isDebugEnabled()){
                            LOGGER.debug("为Id是"+item.getId()+"生成二维码失败");
                        }
                    }

                }else {
                    qrcodeUrl=item.getQrcodeUrl();
                }
                row.addProperty("qrcodeUrl",qrcodeUrl);
                row.addProperty("createtime", DateUtil.DateToStr(item.getCreatetime(),DateUtil.DATE_TIME_PATTERN));
                rows.add(row);
            }
            jsonObject.add("rows",rows);
        }
        return jsonObject.toString();
    }

    //用于测试springboot的返回json问题
    @RequestMapping(value = "/jsonListAli",method = RequestMethod.POST)
    @ResponseBody
    public JSONObject jsonList(SysOss sysOss, PageInfo<SysOss> pageInfo){
        int pageNum=(pageInfo.getPageNum()/pageInfo.getPageSize())+1;
        pageInfo.setPageNum(pageNum);
        pageInfo = sysOssService.pageInfo(sysOss, pageInfo.getPageSize(), pageInfo.getPageNum());
        JSONObject jsonObject=new JSONObject();
        jsonObject.put("total",pageInfo.getTotal());
        if(pageInfo !=null && pageInfo.getList() !=null && pageInfo.getList().size() > 0){
            JSONObject row = null;
            JSONArray rows = new JSONArray();
            List<SysOss> sysOssList=pageInfo.getList();
            for(SysOss item:sysOssList){
                row=new JSONObject();
                row.put("id",item.getId());
                row.put("url",item.getUrl());
                row.put("createtime", DateUtil.DateToStr(item.getCreatetime(),DateUtil.DATE_TIME_PATTERN));
                rows.add(row);
            }
            jsonObject.put("rows",rows);
        }
        return jsonObject;
    }

    /**
     * 新增图片
     */
    @RequestMapping(value = "/UpdateOrAddEntity",method = RequestMethod.POST)
    @ResponseBody
    public JSONObject UpdateOrAddEntity(HttpServletRequest request, SysOss sysOss, @RequestParam(value="myfiles",required=false)MultipartFile[] myfiles) throws IOException {
        ReturnInfo returnInfo=new ReturnInfo();
        JSONObject jsonObject=new JSONObject();
        //上传
        FileUploadUtil fileUploadUtil=new FileUploadUtil();
        List<String> urlList = fileUploadUtil.uplodCompress(myfiles);
        if(urlList.isEmpty()){
            if (LOGGER.isDebugEnabled()){
                LOGGER.debug("上传图片失败！");
            }
            returnInfo=new ReturnInfo(BaseConstant.FAIL, "上传图片失败！");
        }else{
            //保存到数据库
            List<SysOss> sysOssList=new ArrayList<>();
            for (String url:urlList){
                SysOss record=new SysOss();//主键自增
                record.setUrl(url);
                record.setCreatetime(new Date());
                sysOssList.add(record);
            }
            int info=sysOssService.insertSysOssList(sysOssList);

            if (info<0){
                LOGGER.error("图片路径保存进入数据库失败！");
                returnInfo=new ReturnInfo(BaseConstant.FAIL, "图片路径保存进入数据库失败！");
            }

        }

        jsonObject.put("returnInfo",returnInfo);
        return jsonObject;
    }

}
